class Cpanel::PostsController < Cpanel::BaseController

  before_action :find_post, only: [:edit, :show, :update, :destroy]

  def index
    @posts = Post.by_created_at_desc.paginate(page: params[:page], per_page: 10)
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new post_params
    if @post.save
      update_photo(@post, params[:photo_id]) unless params[:photo_id].blank?
      redirect_to [:cpanel, @post], notice: 'create success'
    else
      render 'new'
    end
  end

  def show
  end

  def edit
  end

  def update

    if params[:post][:front_img].blank?
      params[:post].delete :front_img
    end

    if @post.update_attributes(post_params)
      update_photo(@post, params[:photo_id]) unless params[:photo_id].blank?
      redirect_to [:cpanel, @post], notice: 'update success'
    else
      flash[:notice] = 'update faild'
      render 'edit'
    end
  end

  def destroy
    @post.destroy
    redirect_to cpanel_posts_path, notice: 'delete success'
  end

  private

  def find_post
    @post = Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:title, :content, :language, :front_img)
  end

  def update_photo(post, ids)
    ids.each do |id|
      Photo.find(id).update_attributes(photoable: post)
    end
  end

end
